package com.nuanshui.heatedloan.module.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.nuanshui.heatedloan.module.facade.ModuleService;
import com.nuanshui.heatedloan.module.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.nuanshui.heatedloan.baseservice.service.CommonServiceImpl;
import com.nuanshui.heatedloan.service.services.CommonTool;
import com.nuanshui.heatedloan.baseservice.facade.ImageService;
import com.nuanshui.heatedloan.dal.IdTypeHandler;
import com.nuanshui.heatedloan.constant.FeatureType;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.constant.DubboCacheRegion;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.constant.TransactionManagerType;
import com.nuanshui.heatedloan.dubbo.extension.cache.manager.DubboCacheManager;
import com.nuanshui.heatedloan.module.dal.mapper.ModuleMapper;
import com.nuanshui.heatedloan.module.features.IFeatureManager;
import com.nuanshui.heatedloan.userinfo.facade.UserService;
import com.nuanshui.heatedloan.userinfo.tool.UserTool;

@Service
@Transactional(readOnly = true, value = TransactionManagerType.MODULE_TRANSACTION_MANAGER)
public class ModuleServiceImpl extends CommonServiceImpl implements ModuleService {

	@Autowired
	private ModuleMapper moduleMapper;

	@Autowired
	private CommonTool commonTool;
	
	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserTool userTool;

	@Autowired
	private IFeatureManager featureManager;

	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserService userService;

	private static final Logger logger = LoggerFactory.getLogger("service_module");

	@Reference(url = GlobalParam.BASESERVICE_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version=GlobalParam.BASESERVICE_DUBBO_SERVER_VERSION)
	private ImageService imageService;
	
	@Autowired
	private DubboCacheManager dubboCacheManager;
	
	private List<Feature> getInternalModuleList(String moduleId) {
		List<Feature> list = moduleMapper.getBaseModuleList(Integer.parseInt(moduleId));

		for (Feature feature : list) {
			List<FeatureItem> items = moduleMapper.getFeatureItems(feature.getFeatureId());
			feature.setInternalData(items);
		}
		return list;
	}

	@Override
	public List<Feature> getModuleList(String moduleId) {
		List<Feature> list = (List<Feature>) dubboCacheManager.get(DubboCacheRegion.CHACHE_PERSONAL_MODULE_LIST,moduleId);
		if(list==null){
			list = getInternalModuleList(moduleId);
			dubboCacheManager.put(DubboCacheRegion.CHACHE_PERSONAL_MODULE_LIST,moduleId,list);
		}

		for (Feature feature : list) {
			FeatureForm form = new FeatureForm();
			form.setItem(feature);
			handleFeature(form);
		}
		return list;
	}

	private void handleFeature(FeatureForm item) {
		featureManager.handleFeature(item);
	}




	@Override
	public List<Feature> getPersonModule() {
		List<Feature> module = getModuleList("2");
		return module;
	}
	@Override
	public Feature getFeatureByFeatureId(String featureId) {
		return moduleMapper.getFeatureByFeatureId(featureId);
	}
	public void updateModule(String featureJsonValues, Integer moduleId) {
		// 解析json，得到需要更新的数据
		List<Feature> featureList = JSON.parseArray(featureJsonValues, Feature.class);

		ModuleForm form=new ModuleForm();
		form.setModuleId(moduleId);
		form.setIsEditRequest(1);

		// 先查询出当前模块下面的所有的feature。
		Module module = moduleMapper.getModuleWithFeatureById(form);
		List<Feature> featureListAll = module.getList();

		StringBuilder sbNeedUpdateId = new StringBuilder();
		StringBuilder sbNeedDeleteId = new StringBuilder();
		StringBuilder sbAllId = new StringBuilder();

		// 先得到所有的id。
		for (Feature feature : featureListAll) {
			sbAllId.append(feature.getId() + ",");
		}
		String[] allIds = sbAllId.toString().split(",");

		// 得到网页带过来的需要更新的数据的id
		for (Feature feature : featureList) {
			sbNeedUpdateId.append(feature.getId() + ",");
		}
		String[] needUpdateIds = sbNeedUpdateId.toString().split(",");
		LogUtil.info(logger, ">>>>>>>>>>>>>当前要更新的featureid是>>>" + sbNeedUpdateId.toString() + "<<<<<<<<<<<<");

		// 查找出网页没带过来的id，执行删除。
		boolean flag; // 用来记住当前这个id，是否需要删除
		for (String allId : allIds) {
			flag = true;
			for (String needUpdateId : needUpdateIds) {
				if (allId.equals(needUpdateId)) {// 如果网页带过来的数据里面有这个id，则表示当前这个feature不需要删除
					flag = false;
					continue;
				}
			}
			if (flag) {
				sbNeedDeleteId.append(allId + ",");
			}
		}
		String[] sbNeedDeleteIds = sbNeedDeleteId.toString().split(",");
		LogUtil.info(logger, ">>>>>>>>>>>>>当前要删除的featureid是>>>" + sbNeedDeleteId.toString() + "<<<<<<<<<<<<");

		// 删除操作
		for (Feature feature : featureListAll) {
			for (String needDeleteId : sbNeedDeleteIds) {
				if (feature.getId().equals(needDeleteId)) {// 判断当前这个feature是否已经在页面被删除
					LogUtil.info(logger,
							">>>>>>>>>>>>>当前要删除的featureid是>>>" + IdTypeHandler.decode(needDeleteId) + "<<<<<<<<<<<<");
					moduleMapper.deleteFeatureByFeatureId(feature.getId());
					moduleMapper.deleteFeatureItemByFeatureId(feature.getFeatureId());
				}
			}
		}

		// 校验更新操作
		for (Feature feature : featureList) {
			Map<String, Object> msg = checkModule(feature);
			if (msg.get("isPass") != null && ((boolean) msg.get("isPass")) == false)
				error(msg.get("erroeMsg").toString());

			// 如果都通过了，执行更新排序操作
			moduleMapper.updateFeature(feature);
		}
	}

	/**
	 * 判断当前的feature下面的featureitem是否是正确的格式。--就是校验一下item的数据
	 * 
	 * @param feature
	 * @return
	 */
	private Map<String, Object> checkModule(Feature feature) {
		Map<String, Object> msg = new HashMap<String, Object>(2);
		boolean flag = true;

		List<Feature> featureList = moduleMapper.findFeatureItemByFeatueId(feature.getFeatureId());
		switch (feature.getModuleId()) {
		case FeatureType.FEATURETYPE_ELITEBANNER: // 精选大banner，是否最少有4个item,
			break;
		case FeatureType.FEATURETYPE_ELITETHUMBBANNER: // 4ICON是否只有4个item
			if (featureList.size() != 4) {
				flag = false;
			}
			msg.put("erroeMsg", "ICON的item只有" + featureList.size() + "个，只能有4个");
			break;

		}
		msg.put("isPass", flag);
		return msg;
	}	

	public static void main(String[] args) {
		Map<String,String> map = new HashMap<String,String>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		String extData = "{\"rightText\":\""+sdf.format(new Date()) + "到期\"}";
		map.put("rightText", extData);
		
		System.out.println(extData);
	}
	
	
}
